<template>
  <div id="dialogMenu">
    <el-dialog
      :title="isAdd ? '添加菜单' : '编辑菜单'"
      :visible.sync="dialogData.isShow"
      :before-close="labelHandleClose"
      width="550px"
    >
      <div class="form-box">
        <el-form ref="ruleForm" :model="form" :rules="formRules">
          <el-form-item label="上级菜单" label-width="90px" prop="rolesName">
            <el-input v-model="form.parentName" @focus="showSelectMenu">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="菜单类型" label-width="90px" prop="menuType">
            <template>
              <el-radio v-model="form.menuType" label="M">
                目录
              </el-radio>
              <el-radio v-model="form.menuType" label="C">
                菜单
              </el-radio>
              <el-radio v-model="form.menuType" label="F">
                按钮
              </el-radio>
            </template>
          </el-form-item>
          <el-form-item label="菜单名称" label-width="90px" prop="menuName">
            <el-input v-model.trim="form.menuName"></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.menuType === 'C'"
            key="请求地址"
            label="请求地址"
            label-width="90px"
            prop="url"
          >
            <el-input v-model="form.url"></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.menuType !== 'M'"
            key="权限标识"
            label="权限标识"
            label-width="90px"
            prop="perms"
          >
            <el-input v-model="form.perms"></el-input>
          </el-form-item>
          <el-form-item label="显示排序" label-width="90px" prop="orderNum">
            <el-input v-model.trim="form.orderNum"></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.menuType === 'M'"
            key="图标"
            label="图标"
            label-width="90px"
            prop="icon"
          >
            <el-input
              v-model="form.icon"
              placeholder="请选择图标"
              name="icon-input"
              @focus="changeShowIcon(1)"
            ></el-input>
            <div
              class="icon-box"
              :style="{ display: showIcon ? 'block' : 'none' }"
            >
              <div class="icon-list">
                <i
                  v-for="(item, index) in iconList"
                  :key="index"
                  :class="['fa', item.className]"
                  @click="chooseIcon(item)"
                ></i>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="菜单状态" label-width="90px">
            <template>
              <el-radio
                v-for="item in statusList"
                :key="item.dictValue"
                v-model="form.visible"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">
          取 消
        </el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 菜单选择弹出框 -->
    <SelectMenu
      ref="selectMenu"
      width="30%"
      @getDepartName="getDepartName"
    ></SelectMenu>
  </div>
</template>
<script>
import {
  repeatMenuName,
  getMenuDetail,
  editMenu,
  addMenu
} from '@/api/system/menu' // 接口
import SelectMenu from '@component/system/menu/selectMenu' // 选择菜单
import { sysNormalDisable } from '@utils/dictionariesFunc'
export default {
  name: 'RoleAddEdit',
  msg: '菜单管理-新增/编辑弹窗',
  components: {
    SelectMenu
  },
  props: ['dialogData'],
  data() {
    var valiSort = (rule, value, callback) => {
      if (value !== 0 && !value) {
        callback(new Error('显示排序不能为空'))
      } else {
        if (isNaN(value)) {
          callback(new Error('显示排序必须为数字值'))
        } else {
          callback()
        }
      }
    }
    var valiName = (rule, value, callback) => {
      let obj = {
        menuName: this.form.menuName,
        parentId: this.form.parentId,
        menuId: this.form.menuId
      }
      repeatMenuName(
        obj,
        (response) => {
          if (response) {
            //true-无重复
            callback()
          } else {
            //false-有重复
            callback(new Error('该菜单名称已使用'))
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    return {
      isAdd: true, // 新增-true,编辑-false
      showTitle: '',
      loading: false,
      showIcon: false,
      statusList: [],
      // 表单数据
      form: {
        parentName: '', // 上级菜单名称
        menuId: '', // 菜单id
        parentId: '', // 父级id
        menuType: 'M', // 类型:M目录,C菜单,F按钮
        menuName: '', // 菜单名称
        url: '', // 菜单URL
        perms: '', // 权限标识
        orderNum: '', // 显示顺序
        icon: '', // 菜单图标
        visible: '0' // 菜单状态:0显示,1隐藏
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      formRules: {
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { validator: valiName, trigger: 'blur' }
        ],
        orderNum: [{ required: true, validator: valiSort, trigger: 'blur' }]
      }
    }
  },
  computed: {
    iconList() {
      return this.$store.getters.iconList
    }
  },
  mounted() {
    this.hideSelect()
    this.getStatusList()
    this.isAdd = this.dialogData.type === 'add'
    this.showTitle = this.isAdd ? '新增' : '编辑'
    if (this.isAdd && !this.dialogData.params) {
      // 新增
      this.form.parentId = 0
      this.form.parentName = '主目录'
    }
    if (this.isAdd && this.dialogData.params) {
      // 添加下级菜单
      let params = this.dialogData.params
      this.form.parentId = params.menuId
      this.form.parentName = params.menuName
    }
    if (this.dialogData.type === 'edit') {
      this.form.menuId = this.dialogData.params
      this.getFormData()
    }
  },
  methods: {
    /* 获取菜单状态 */
    async getStatusList() {
      this.statusList = await sysNormalDisable('sys_show_hide', '')
    },
    /* 编辑时获取表单详情 */
    getFormData() {
      getMenuDetail(this.form.menuId, (response) => {
        let obj = response
        for (let key in this.form) {
          this.form[key] = obj[key]
        }
        if (obj.parentId === 0) {
          this.form.parentName = '主目录'
        }
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.params = null
    },
    // 显示菜单选择弹窗
    showSelectMenu() {
      this.$refs.selectMenu.showModel()
    },
    // 选择图标
    chooseIcon(item) {
      this.form.icon = `fa ${item.className}`
    },
    // 显示图标列表
    changeShowIcon() {
      this.showIcon = true
    },
    /* 事件委托隐藏图标列表 */
    hideSelect() {
      var _this = this
      document.body.onclick = function(e) {
        e = e || window.event
        var curEle = e.target || e.srcElement
        if (
          curEle.className.includes('icon-box') ||
          (curEle.name && curEle.name.includes('icon-input'))
        ) {
        } else {
          _this.showIcon = false
        }
      }
    },
    /* 确定 */
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.subForm()
        } else {
          return false
        }
      })
    },
    /* 提交表单 */
    subForm() {
      this.loading = true
      let obj = { ...this.form }

      if (this.isAdd) {
        // 新增
        delete obj.menuId
        addMenu(
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message({
              message: this.showTitle + '失败，' + response.msg,
              type: 'warning'
            })
          }
        )
      } else {
        // 编辑
        delete obj.parentName
        editMenu(
          this.form.menuId,
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message({
              message: this.showTitle + '失败，' + response.msg,
              type: 'warning'
            })
          }
        )
      }
    },
    /* 子组件选择菜单后，给上级菜单赋值 */
    getDepartName(selectNode) {
      if (!selectNode.menuId) return
      this.form.parentId = selectNode.menuId
      this.form.parentName = selectNode.menuName
    }
  }
}
</script>
<style lang="less">
#dialogMenu {
  .el-dialog {
    border-radius: 4px;

    .el-dialog__header {
      border-bottom: 1px solid rgba(225, 228, 233, 1);
    }
  }

  .el-dialog__wrapper {
    z-index: 3000 !important;
  }

  .icon-box {
    width: 100%;
    height: 200px;
    overflow: auto;

    .icon-list {
      width: 100%;
      height: 400px;

      .fa {
        margin: 5px;
        padding: 5px;
        cursor: pointer;
        font-size: 18px;
        width: 28px;
        border-radius: 3px;
        text-align: center;

        &:hover {
          background-color: #1d9d74;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
